package cn.lxh.user.service.impl;

import cn.lxh.basic.constant.BaseConstant;
import cn.lxh.basic.dto.LoginDto;
import cn.lxh.basic.dto.WechatDto;
import cn.lxh.basic.exception.BusinessException;
import cn.lxh.basic.service.impl.BaseServieceImpl;
import cn.lxh.basic.utils.HttpClientUtils;
import cn.lxh.basic.utils.MD5Utils;
import cn.lxh.basic.utils.StrUtils;
import cn.lxh.org.basic.utils.AjaxResult;
import cn.lxh.user.domain.Logininfo;
import cn.lxh.user.domain.User;
import cn.lxh.user.domain.Wxuser;
import cn.lxh.user.mapper.LogininfoMapper;
import cn.lxh.user.mapper.UserMapper;
import cn.lxh.user.mapper.WxuserMapper;
import cn.lxh.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxh
 * @since 2022-06-17
 */
@Service
public class LogininfoServiceImpl extends BaseServieceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private  UserMapper userMapper;

    @Override
    public Map<String, Object> account(LoginDto dto) {
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        if(
                StringUtils.isEmpty(password) || StringUtils.isEmpty(username) || StringUtils.isEmpty(type)
        ){
            throw  new BusinessException("空检验,你输入的是空的");
        }
        Logininfo logininfo = logininfoMapper.findByusernameAndType(username,type);
        if(logininfo == null){
            throw  new BusinessException("这个用户不存在或者账户不存在");
        }
        // 查到了，校验密码是否一致
        //密码需要加密加盐

        String salt = logininfo.getSalt();
        String md5pwd = MD5Utils.encrypByMd5(password + salt);
        if(!md5pwd .equals(logininfo.getPassword())){
            throw new BusinessException("密码不正确");
        }
        //登录成功 存入redis中
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();

        map.put("token",token);
        map.put("logininfo",logininfo);
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        return map;
    }

    /**
     * 微信登录，已经注册过，直接登录逻辑
     * 没有注册过。到注册页面
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        String code = dto.getCode();
        //code空检验
        if(StringUtils.isEmpty(code)){
            throw  new BusinessException("code为空");
        }
        String tokenUrl = BaseConstant.WeChatConstants.TOKEN_URL
                .replace("APPID",BaseConstant.WeChatConstants.APPID)
                .replace("SECRET",BaseConstant.WeChatConstants.SECRET)
                .replace("CODE",code);

        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
         //转换成json对象。从json对选哪个中拿到accessToken
            JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
        //从微信表中找
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        //有这个人
        if(wxuser != null && wxuser.getUserId()!=null){
            //从longinfo中去找到这个人 存在redis中
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            //4.1 存储redis uuid
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("logininfo",logininfo);
            logininfo.setSalt(null);
            logininfo.setPassword(null);
            return AjaxResult.me().setResultObj(map);
        }
        //没有这个人跳转绑定页面
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    @Override
    public Map<String, Object> binder(WechatDto dto) {
        String phone = dto.getPhone();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        if (StringUtils.isEmpty(phone)){
            throw  new BusinessException("你没有输入账号");
        }
        if (StringUtils.isEmpty(accessToken)||StringUtils.isEmpty(openId)){
            throw  new BusinessException("你没有输入accessToken或者openId");
        }
        //1.根据username 查询t_user是否曾今已经存在
        User user = userMapper.findByUsername(phone);
        //有这个人
        Logininfo logininfo =null;
        if(user !=null){
            logininfo = logininfoMapper.findByUserId(user.getId());
        }else {
 //        1.2 不存在 生成新的t_user + t_logininfo
            user= dto2User(dto);
            logininfo =user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }

//        2.根据token + openid 去微信查询微信的用户基本信息   ③
        String wxTokenUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserStr = HttpClientUtils.httpGet(wxTokenUrl);
         //根据微信的用户基本信息生成t_wxuser
        Wxuser wxuser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        //拿到微信相关的信息
        System.out.println(wxuser);

        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //绑定过程结束 开始redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //我们是高级技师，应该考虑到一些敏感信息不要返回给前端
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        logininfo.setType(1);
        BeanUtils.copyProperties(user,logininfo);
        return logininfo;

    }
    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }
}
